﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace XNA_Game_Engine.GUI
{
    public class Buttons
    {
        private Texture2D _sprite;
        private readonly Texture2D _spriteDefault;
        private readonly Texture2D _spriteWhenClicked;
        private readonly Texture2D _spriteWhenDisabled;
        public Rectangle ThisObject { get; private set; }

        public bool Enabled;
        private bool _mouseClicked;
        private double _keepClickTime;

        public Action MouseReleased;

        public Buttons(Texture2D defaultSprite, Texture2D clickedSprite, Texture2D spriteWhenDisabled, Rectangle objectPosition, bool enabled)
        {
            ThisObject = objectPosition;

            _sprite = defaultSprite;
            _spriteDefault = defaultSprite;
            _spriteWhenClicked = clickedSprite;
            _spriteWhenDisabled = spriteWhenDisabled;
            _mouseClicked = false;
            _keepClickTime = 0;
            SetEnabled(enabled);

            MouseReleased = null;
        }

        public void Update(GameTime gameTime)
        {
            if (!Enabled)
                return;

            if (!StaticGui.IsMouseBeingUsed() && StaticGui.MouseState.LeftButton == ButtonState.Pressed && StaticGui.MouseColision(ThisObject) && CheckTime(gameTime, _keepClickTime))
            {
                if (MouseReleased == null)
                    return;

                _mouseClicked = true;
                StaticGui.UsingMouse(true);
                _sprite = _spriteWhenClicked;

                _keepClickTime = gameTime.TotalGameTime.TotalMilliseconds;
            }

            if (!_mouseClicked)
                return;

            if (StaticGui.MouseState.LeftButton == ButtonState.Pressed)
                return;

            _mouseClicked = false;
            StaticGui.UsingMouse(false);

            _sprite = _spriteDefault;

            if (MouseReleased != null && StaticGui.MouseColision(ThisObject))
                MouseReleased();
        }

        public void Draw(SpriteBatch render)
        {
            //render.Draw(_sprite, new Vector2(ThisObject.X, ThisObject.Y), Color.White);
            Rectangle drawRect = new Rectangle(ThisObject.X, ThisObject.Y, ThisObject.Width, ThisObject.Height);
            Rectangle targetRect = new Rectangle(0, 0, _sprite.Width, _sprite.Height);
            render.Draw(_sprite, drawRect, targetRect, Color.White);
        }

        public void SetEnabled(bool enabled)
        {
            Enabled = enabled;
            _sprite = Enabled ? _spriteDefault : _spriteWhenDisabled;
        }

        private static bool CheckTime(GameTime gameTime, double time)
        {
            return time + 200 < gameTime.TotalGameTime.TotalMilliseconds;
        }

    }
}
